define([
  'jquery',
  'backbone',
  'utils/Logger',
  'collections/AlertMessages',
  'hbs!template/loading'
], function($, Backbone, Logger, AlertMessages, loadingTemplate){
  
  var View = Backbone.View.extend({
    initialize: function(options) {
      options || (options = {});
      Backbone.View.prototype.initialize.call(this, options);
      
      if(options.messages) {
        this.messages = options.messages;
      }

      // Loading...
      if(this.collection) {
        this.collection.bind("loading", this.showLoading, this);
      }
      if(this.model) {
        this.model.bind("loading", this.showLoading, this);
      } 
    },
    
    render: function() {
      if(this.template) {
        $(this.el).html(this.template(this.serialize ? this.serialize() : this.getRenderData()));
      }
      return this;
    },
    
    getRenderData: function() {
      if(this.model) {
        return this.model.toJSON();
      } else {
        return {};
      }
    },

    serialize: function() {
      return this.getRenderData();
    },
    
    open: function() {
      $(this.el).show();
    },

    close: function() {
      //console.log("ModalForm-> closing");
      $(this.el).modal('hide');
      this.remove();
      this.unbind();
    },
    
    addMessage: function(message) {
      if(this.messages) {
        this.messages.add(message);
      } else {
        console.log("NO messages in the view!!!!");
      }
    },
    
    back: function() {
      history.back();
    },

    showLoading: function() {
      $(this.el).html(loadingTemplate());
    }
  });

  View.prototype.Logger = Logger;
  
  return View;
});